﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Data.OleDb;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Ultimus.OC;
using Ultimus.WFServer;
using UServLib;
using H2.NET.Common;
using H2.NET.Web.Workflow.DwzCode;
using H2.NET.Web.Workflow.Helpers;
using System.Collections.Generic;

namespace H2.NET.Web.Workflow
{
    public partial class Inbox : BasePage
    {
        #region 属性 public
        private DataTable dt = new DataTable();

        private DataTable allProcess = new DataTable();

        /// <summary>
        /// 列表固定样式
        /// </summary>
        public string Style = "fixed"; 

        [SessionType]
        string strProcessName = "";

        //类型
        public string Type
        {
            get
            {
                return this.ViewState["Type"] == null ? "" : (String)this.ViewState["Type"];
            }
            set
            {
                this.ViewState["Type"] = value;
            }
        }
        #endregion
        private string DatabaseName
        {
            get
            {
                if (Application["DBName"] == null)
                {
                    var connStr = H2.NET.Util.ConnectionStrings("oleDB");
                    var conn = new OleDbConnection(connStr);
                    Application["DBName"] = conn.Database;
                    conn.Dispose();
                }
                return Application["DBName"] as string;
            }
        }


        #region 事件 页面 加载
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                load_gv_inbox_list();
                initSelectItem();
                hf_type.Value = AksRequest.GetString("drpProcess").Trim();
                if (inboxStyle.Value != "")
                {
                    Session["inboxStyle"] = inboxStyle.Value;
                }
                Style = Session["inboxStyle"] == null ? Style : Session["inboxStyle"].ToString();
                inboxStyle.Value = Style;
            }
            catch (Exception ee)
            {
                TaskDB.Log("", false, "调用 inbox.aspx 页面 Page_Load 事件出错：" + ee.Message);
            }
        }
        #endregion

        #region 给流程列表初始化字段（图片，用户账号，姓名等）
        public void load_gv_inbox_list()
        {
           
            try
            {
                //加载列表
                dt = get_all_inbox();
                allProcess = get_all_process();

                //数据合法性检查
                if (dt == null)
                {
                    return;
                }

                #region added by zk 2009-12-21 start
                //取得所有的用户账号对应用户姓名             
                string str_user_name = "";
                DataTable dt2 = new DataTable();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    //initiator
                    if (str_user_name.IndexOf(",'" + dt.Rows[i]["initiator"].ToString().Trim() + "'") == -1)
                    {
                        str_user_name += ",'" + dt.Rows[i]["initiator"].ToString().Trim() + "'";
                    }

                    //taskuser
                    if (str_user_name.IndexOf(",'" + dt.Rows[i]["taskuser"].ToString().Trim() + "'") == -1)
                    {
                        str_user_name += ",'" + dt.Rows[i]["taskuser"].ToString().Trim() + "'";
                    }

                    //assignedtouser
                    if (str_user_name.IndexOf(",'" + dt.Rows[i]["assignedtouser"].ToString().Trim() + "'") == -1)
                    {
                        str_user_name += ",'" + dt.Rows[i]["assignedtouser"].ToString().Trim() + "'";
                    }
                }

                //从数据库中查询用户信息
                string strSQL = "select rtrim(FULLNAME) as UserFullName,lower(rtrim(Name)) as UserShortName from JOBS where lower(rtrim(Name)) in('-1'" + str_user_name + ")";
                clsCmm.clsDB.Storage("bpmDB");
                dt2 = clsCmm.clsDB.Query(strSQL);
                #endregion added by zk 2009-12-21 end

                //设置状态列的图片
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    //处理表单类型 (自定义表单 & 标准表单)
                    string HelpUrl = dt.Rows[i]["helpurl"].ToString();

                    Dictionary<string, string> parms = new Dictionary<string, string>();
                    parms.Add("taskId", dt.Rows[i]["taskid"].ToString());
                    parms.Add("incident", dt.Rows[i]["incident"].ToString());

                    dt.Rows[i]["openform"] = UltimusHelper.ResolveUrl(dt.Rows[i]["helpurl"].ToString().Trim(),
                                                                    parms,
                                                                    dt.Rows[i]["processname"].ToString().Trim());

                    #region added by zk 2009-12-21 start
                    //循环设置用户信息
                    for (int j = 0; j < dt2.Rows.Count; j++)
                    {
                        //initiator
                        if (dt.Rows[i]["initiator"].ToString().ToLower().Trim() == dt2.Rows[j]["UserShortName"].ToString().ToLower().Trim())
                        {
                            dt.Rows[i]["initiator_name"] = dt2.Rows[j]["UserFullName"].ToString().Trim();
                        }

                        //taskuser
                        if (dt.Rows[i]["taskuser"].ToString().ToLower().Trim() == dt2.Rows[j]["UserShortName"].ToString().ToLower().Trim())
                        {
                            dt.Rows[i]["taskuser_name"] = dt2.Rows[j]["UserFullName"].ToString().Trim();
                        }

                        //assignedtouser
                        if (dt.Rows[i]["assignedtouser"].ToString().ToLower().Trim() == dt2.Rows[j]["UserShortName"].ToString().ToLower().Trim())
                        {
                            dt.Rows[i]["assignedtouser_name"] = dt2.Rows[j]["UserFullName"].ToString().Trim();
                        }
                    }
                    #endregion added by zk 2009-12-21 end

                    //流程状态图标
                    switch (dt.Rows[i]["substatus"].ToString().Trim())
                    {
                        case "0":
                        case "1":
                            dt.Rows[i]["img_status"] = "frm_inbox_late.gif";
                            break;

                        case "2":
                            dt.Rows[i]["img_status"] = "frm_inbox_overdue.gif";
                            break;

                        case "3":
                            dt.Rows[i]["img_status"] = "frm_inbox_urgent.gif";
                            break;

                        case "4":
                            dt.Rows[i]["img_status"] = "frm_inbox_reassigned.gif";
                            break;

                        case "7":
                            dt.Rows[i]["img_status"] = "frm_inbox_urgent.gif";
                            break;

                        case "8":
                            dt.Rows[i]["img_status"] = "frm_inbox_reassigned.gif";
                            break;

                        case "16":
                            dt.Rows[i]["img_status"] = "frm_inbox_returned.gif";
                            break;

                        case "32":
                            dt.Rows[i]["img_status"] = "frm_inbox_resubmitted.gif";
                            break;

                        default:
                            dt.Rows[i]["img_status"] = "frm_initiate_blank.gif";
                            break;
                    }

                    //判断是否为指派、会办的任务类型
                    if (dt.Rows[i]["taskuser"].ToString() != dt.Rows[i]["assignedtouser"].ToString())
                    {
                        dt.Rows[i]["img_status"] = "frm_inbox_reassigned.gif";
                    }

                    //是否显示监控图标
                    if (dt.Rows[i]["taskid"] == DBNull.Value || dt.Rows[i]["taskid"].ToString().Trim() == "")
                    {
                        dt.Rows[i]["img_monitor"] = "frm_initiate_blank.gif";
                        dt.Rows[i]["img_status"] = "frm_initiate_blank.gif";
                    }
                    else
                    {
                        dt.Rows[i]["img_monitor"] = "bpmview.gif";
                    }

                }

                //第一次没有排序字段的情况
                //if (ViewState["OrderBy"] == null)
                //{
                //    dt.DefaultView.Sort = "starttime DESC";
                //}
                //else
                //{
                //    dt.DefaultView.Sort = ViewState["OrderBy"] + " " + ViewState["Order"];
                //}

                gvInbox.DataSource = dt;
                gvInbox.DataBind();

            }
            catch (Exception ee)
            {
                TaskDB.Log("", false, "调用 inbox.aspx 页面 load_gv_inbox_list 方法出错：" + ee.Message);
            }
        }
        #endregion   

        #region 获取当前用户代办流程的数据
        public DataTable get_all_inbox()
        {
            try
            {
                string strUserName = clsCmm.comm_username;
                string strSummary = "";
                string strIncidentNoFrom = txtIncidentFrom.Value;
                string strIncidentNoTo = txtIncidentTo.Value;

                //查询过滤中Process下拉列表中的值
                string strProcess = "all";
                if (drpProcess.SelectedItem != null)
                {
                    strProcess = drpProcess.SelectedItem.Value.Trim();
                }
                else 
                {
                    if (!AksRequest.GetQueryString("process").Equals(""))
                    {
                        strProcess = AksRequest.GetQueryString("process").Trim();
                    }
                }

                //查询过滤中流程步骤的值
                string strStep = "all";
                if (drpStep.SelectedItem != null)
                {
                    strStep = drpStep.SelectedItem.Value.Trim();
                }
                else
                {
                    if (!AksRequest.GetQueryString("step").Equals(""))
                    {
                        strStep = AksRequest.GetQueryString("step").Trim();
                    }
                }

                //查询过滤中摘要的值
                strSummary = tb_Summary.Text.Trim();
                if (strSummary.Equals(""))
                {
                    if (!AksRequest.GetQueryString("remark").Equals(""))
                    {
                        strSummary = AksRequest.GetQueryString("remark").ToString().Trim();
                    }
                }
                tb_Summary.Text = strSummary;
                //查询过滤中序号的值


                //查找收件箱列表
                var sql = new System.Text.StringBuilder();
                sql.AppendLine(@"SELECT  CASE ISNULL(ISNULL(p.DMO_Priority, p.Business_Priority), 3)
                                  WHEN 1 THEN 'Urgent'
                                  WHEN 2 THEN 'High'
                                  WHEN 3 THEN 'Routine'
                                END AS [Priority] ,
                                RTRIM(a.taskid) AS taskid ,");
                if (clsCmm.comm_language == "en-us" && Util.AppSettings("language").ToLower() == "yes")
                {
                    sql.AppendLine(" h.processhelpurl as processname3,");
                }
                else
                {
                    sql.AppendLine(" a.processname as processname3,");
                }
                sql.AppendLine(" h.processname,");
                sql.AppendLine(@"RTRIM(a.helpurl) AS helpurl ,
                                '' AS openform ,
                                a.incident ,
                                a.steplabel ,
                                a.taskuser ,
                                a.assignedtouser ,
                                '' AS img_status ,
                                '' AS img_monitor ,
                                a.status ,
                                a.substatus ,
                                a.starttime ,
                                a.delaytime ,
                                a.overduetime ,
                                DATEDIFF(s, GETDATE(), a.urgentduetime) AS urgentduetime ,
                                c.summary ,
                                c.initiator ,
                                '' AS initiator_name ,
                                '' AS taskuser_name ,
                                '' AS assignedtouser_name");
                sql.AppendLine(string.Format(@"FROM    tasks a
                                        LEFT JOIN {0}.dbo.mdc_Priority p ON a.PROCESSNAME = p.Process
                                                                                    AND p.Incident = a.INCIDENT
                                                                                    AND a.taskid NOT IN (
                                                                                    SELECT  taskid
                                                                                    FROM    taskqueue )
                                        INNER JOIN dbo.INITIATE h ON a.PROCESSNAME = h.PROCESSNAME
                                                                     AND H.PROCESSNAME IN (
                                                                     SELECT [PROCESSNAME]
                                                                     FROM   [PROCESSES]
                                                                     WHERE  [PROCESSES].[DESCRIPTION] IN (
                                                                            SELECT  KeyWords
                                                                            FROM    BPMSYSTEM
                                                                            WHERE   Platform = '{1}' ) )
                                        LEFT JOIN incidents c ON a.processname = c.processname
                                                                 AND a.incident = c.incident
                                WHERE   1 = 1", DatabaseName, Util.AppSettings("platform")));
                sql.AppendLine(" and lower(a.assignedtouser) = lower('" + strUserName + "')");
                sql.AppendLine(" and a.status = 1");

                //如果 Type=1 的情况,则表示我的审批   Type=2 的情况,则表示我的申请
                if (this.Type == "1")
                {
                    sql.AppendLine(" and right(rtrim(a.stepid),1) <> 'B'");
                }
                else if (this.Type == "2")
                {
                    sql.AppendLine(" and right(rtrim(a.stepid),1) = 'B'");
                }


                //查询过滤
                if (strProcess != "all")
                {
                    sql.AppendLine(" and a.processname = '" + strProcess + "'");
                }

                //added by
                if (!string.IsNullOrEmpty(strProcessName))
                {
                    sql.AppendLine(" and a.processname = '" + strProcessName + "'");
                }

                if (strStep != "all")
                {
                    sql.AppendLine(" and a.steplabel = '" + strStep + "'");
                }

                if (strIncidentNoFrom != "")
                {
                    sql.AppendLine(" and a.incident >= " + strIncidentNoFrom + "");
                }

                if (strIncidentNoTo != "")
                {
                    sql.AppendLine(" and a.incident <= " + strIncidentNoTo + "");
                }

                //摘要
                if (strSummary != "")
                {
                    sql.AppendLine(" and summary like '%" + strSummary + "%'");
                }

                AppendForCount(sql.ToString());
                clsCmm.clsDB.Storage("bpmDB");
                TotalItemCount = Convert.ToInt32(clsCmm.clsDB.Query(AppendForCount(sql.ToString())).Rows[0][0]);
                PageNumber = Convert.ToInt32(Request.Form["pageNum"] ?? "1");

                
                Pager1.TotalItemCount = TotalItemCount;
                Pager1.PageSize = PageSize;
                Pager1.PageNumber = PageNumber;
                TaskDB.Log("", true, "调用 inbox.aspx 页面 get_all_inbox 方法SQL：" + sql.ToString());

                var r_sql = AppendForPaged(sql.ToString(), PageSize*(PageNumber - 1) + 1, PageSize*PageNumber);
                dt = clsCmm.clsDB.Query(r_sql);

                return dt;
            }
            catch (Exception ee)
            {
                TaskDB.Log("", false, "调用 inbox.aspx 页面 get_all_inbox 方法出错：" + ee.Message);
                return null;
            }
        }

        private string AppendForCount(string sqlStr)
        {
            return string.Format("select count(*) from ({0}) sub", sqlStr);
        }

        private string AppendForPaged(string sqlStr, int start, int end)
        {
            string orderbyfeild = "urgentduetime";
            string orderbydir = "desc";
            //if (ViewState["OrderBy"] != null)
            //{
            //    orderby = ViewState["OrderBy"] + " " + ViewState["Order"];
            //}

            if (!string.IsNullOrEmpty(OrderField))
            {
                orderbyfeild = OrderField;
                orderbydir = OrderDir;
            }
            return string.Format(";with temp as(\r\n" +
                                 "	select row_number() over(order by sub.{3}, sub.starttime desc) as rownum, sub.* from ({0}) sub\r\n)\r\n" +
                                 "select * from temp where rownum between {1} and {2}", sqlStr, start, end,
                orderbyfeild + " " + orderbydir);
        }


        #endregion
        
        #region 获取全部流程
        public DataTable get_all_process()
        {
            string strsql =
                   "select distinct d.PROCESSNAME  from (select b.*, c.summary, c.priority, c.initiator          from (select rtrim(a.taskid) as taskid ,a.processname as processname3 ,a.processname ,rtrim(a.helpurl) as helpurl ,'' as openform ,a.incident ,a.steplabel ,a.taskuser ,a.assignedtouser ,'' as img_status ,'' as img_monitor ,a.status ,a.substatus ,a.starttime ,a.delaytime ,a.overduetime ,a.urgentduetime from tasks a WITH (NOLOCK) , initiate h WITH (NOLOCK)  where 1=1 and a.processname=h.processname AND H.PROCESSNAME IN(SELECT [PROCESSNAME] FROM [PROCESSES] WHERE [PROCESSES].[DESCRIPTION] IN (SELECT KeyWords FROM BPMSYSTEM WHERE Platform = 'MDC'))  and a.taskid not in(select taskid from taskqueue) and lower(a.assignedtouser) = lower('{username}') and a.status = 1 ) b left join incidents c on b.processname = c.processname and b.incident = c.incident) d";
            strsql = strsql.Replace("{username}", clsCmm.comm_username);
            TaskDB.Log("", true, "调用 inbox.aspx 页面 get_all_inbox 方法SQL：" + strsql);

            clsCmm.clsDB.Storage("bpmDB");
            allProcess = clsCmm.clsDB.Query(strsql);
            return allProcess;
        }
        #endregion

        #region 获取流程的step
        public DataTable getStepByProcess(string process) {
            string strSQL = "select * from [PROCESSSTEPS] where processname='" + process + "' and steptype not in (3,5,7)";
            clsCmm.clsDB.Storage("bpmDB");
            return clsCmm.clsDB.Query(strSQL);
        }
        #endregion

        #region 加载选项卡的数据
        public void initSelectItem()
        {
            #region 加载drpProcess选项
            try
            {

                string oldProcess = drpProcess.SelectedValue;

                //清空现有列表
                drpProcess.Items.Clear();

                //增加第一行
                drpProcess.Items.Add(new ListItem("All", "all"));

                //数据合法性检查
                if (dt == null)
                {
                    return;
                }

                #region 获取全部流程的流程名称
                for (int i = 0; i < allProcess.Rows.Count; i++)
                {
                    drpProcess.Items.Add(new ListItem(GetCache(allProcess.Rows[i]["processname"].ToString().Trim()), allProcess.Rows[i]["processname"].ToString().Trim()));
                }
                if (!oldProcess.Equals("all") && !oldProcess.Equals(""))
                {
                    drpProcess.SelectedValue = oldProcess;
                }
                else 
                {
                    if (!AksRequest.GetQueryString("process").Trim().Equals("")) 
                    {
                        drpProcess.SelectedValue = AksRequest.GetQueryString("process").Trim();
                    }
                }
                #endregion
            }
            catch (Exception ex)
            {
                TaskDB.Log("", false, "调用 inbox.aspx 页面 load_drp_control_list方法出错：" + ex.Message);
            }
            #endregion

            #region 加载processStep选项
            processStep();
            #endregion
        }

        #region processStep
        public void processStep()
        {
            String oldStep = drpStep.SelectedValue.Trim();
            drpStep.Items.Clear();
            //增加第一行
            drpStep.Items.Add(new ListItem("All", "all"));
            if (drpProcess.SelectedItem != null && drpProcess.SelectedItem.Value != "all")
            {
                DataTable steps = getStepByProcess(drpProcess.SelectedItem.Value.Trim());
                for (int i = 0; i < steps.Rows.Count; i++)
                {
                    drpStep.Items.Add(new ListItem(GetCache(steps.Rows[i]["steplabel"].ToString().Trim()), steps.Rows[i]["steplabel"].ToString().Trim()));
                }
            }

            if (!oldStep.Equals("all") && !oldStep.Equals(""))
            {
                drpStep.SelectedValue = oldStep;
            }
            else
            {
                if (!AksRequest.GetQueryString("step").Trim().Equals(""))
                {
                    drpStep.SelectedValue = AksRequest.GetQueryString("step").Trim();
                }
            }
        }
        #endregion
        #endregion
    }
}